package nina.yiyou.paystub.input

import nina.yiyou.salary.input.util.ExcelReadOpener
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.xssf.usermodel.XSSFSheet
import org.apache.poi.xssf.usermodel.XSSFWorkbook

import java.nio.file.Path

class TableMetaReader {

  interface Meta {

    double headerHeight()

    List<Employee> rowList()
  }

  interface Employee {

    String id()

    String name()

    int lineIndex()

    double lineHeight()
  }

  TableMetaReader(Path excelPath) {
    _excelPath = excelPath
  }

  Meta read() {
    XSSFWorkbook book = new ExcelReadOpener(_excelPath.toString()).openXlsx()
    XSSFSheet sheet = book.getSheetAt(0)

    List<Row> rowList = (0..sheet.lastRowNum).collect { sheet.getRow(it) }
    def tableHeight = rowList
        .collect { it.heightInPoints }
        .sum() as double

    int dataStart = 4
    def headerHeight = rowList.subList(0, dataStart)
        .collect { it.heightInPoints }
        .sum() as double

    List<Employee> employeeList = rowList.subList(dataStart, rowList.size() - 1)
        .withIndex()
        .collect { readEmployee(it.first, it.second, tableHeight) }

    return new Meta() {
      @Override
      double headerHeight() {
        return headerHeight / tableHeight
      }

      @Override
      List<Employee> rowList() {
        return employeeList
      }
    }
  }

  private Employee readEmployee(Row row, int index, double tableHeight) {
    String id = row.getCell(0).stringCellValue
    String name = row.getCell(1).stringCellValue
    double lineHeight = row.heightInPoints / tableHeight

    return new Employee() {
      @Override
      String id() {
        return id
      }

      @Override
      String name() {
        return name
      }

      @Override
      int lineIndex() {
        return index
      }

      @Override
      double lineHeight() {
        return lineHeight
      }
    }
  }

  private final Path _excelPath
}
